package uk.co.aetherworks.osc_messaging;

/*
 * Ped-ome
 *
 * PedToMon - Sends Messages to Monome Device
 *
 * Joe Handford aka Knecht 2011
 *
 */ 

// OSC Include Files
import com.illposed.osc.OSCPortOut;
import com.illposed.osc.OSCPortIn;
import com.illposed.osc.OSCListener;
import com.illposed.osc.OSCMessage;

// Java Net Include Files

import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

// aetherworks imports
import uk.co.aetherworks.debug.*;
 
public class PedToMon extends Debuggable {

	OSCPortOut sender;
	
	// monListeningPort picked up from selected device service
	public PedToMon(int monListeningPort) {
		DEBUG("** Creating PedToMon bound to port: " + monListeningPort);
		try
        {
            sender = new OSCPortOut(InetAddress.getByName("localhost"), monListeningPort);
        }
        catch (Exception e) { System.out.println("Couldn't create pedome to monome sender!"); }
	}
	
	// Forward message received from app
	public void fwdMsg(OSCMessage msg){
		DEBUG("PedToMon forwarding message from App");
		String address = msg.getAddress();
		Object myArgs[] = msg.getArguments();
		int x = ((Integer) myArgs[0]).intValue();
		int y = ((Integer) myArgs[1]).intValue();
		int state = ((Integer) myArgs[2]).intValue();
		DEBUG("sending " + address + " " + x + " " + y + " " + state);
		try
		{
			sender.send(msg);
		}
		catch (Exception e)
		{
		 System.out.println("Couldn't forward message to monome");
		}
	}
		
	// Send info request
	public void sendInfoReq(int pedListeningPort){
		DEBUG("Sending info request to Monome with Ped listening port flagged as: " + pedListeningPort);
        Object myArgs[] = new Object[2];
//		myArgs[0] = "127.0.0.1";
		myArgs[0] = "localhost";
		myArgs[1] = new Integer(pedListeningPort);

		OSCMessage msg = new OSCMessage("/sys/info", myArgs);

		try
		{
			sender.send(msg);
		}
		catch (Exception e)
		{
		 System.out.println("Couldn't send info req to monome");
		}
	}
	
	// Send pedome listening port
	public void sendPedomeRxPort(int pedListeningPort){
		DEBUG("Sending pedome port to Monome");
        Object myArgs[] = new Object[1];
		myArgs[0] = new Integer(pedListeningPort);

		OSCMessage msg = new OSCMessage("/sys/port", myArgs);

		try
		{
			sender.send(msg);
		}
		catch (Exception e)
		{
		 System.out.println("Couldn't send pedome rx port to monome");
		}
	}
	
	public void sendPedomePrefix(String prefix) {
		DEBUG("Sending pedome prefix to Monome");
        Object myArgs[] = new Object[1];
		myArgs[0] = prefix;

		OSCMessage msg = new OSCMessage("/sys/prefix", myArgs);

		try
		{
			sender.send(msg);
		}
		catch (Exception e)
		{
		 System.out.println("Couldn't send pedome prefix to monome");
		}
	}

	public void close() {
		sender.close();
	}
}